package client;

import gui.graphLabel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import customLayouts.VerticalFlowLayout;

import model.Sensor;

public class PropertiesPopup {

	private Sensor sensor;
	JSpinner upperPicker, lowerPicker;
	JFrame popup;
	
	public PropertiesPopup(Sensor sen){
		sensor = sen;
		popup = new JFrame("Properties of sensor: " + sensor.getName());
		popup.setSize(300, 600);
		popup.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		
		JPanel info = new JPanel();
		info.setLayout(new VerticalFlowLayout());
		JLabel sensorName = new JLabel("Sensor Name: " + sensor.getName());
		info.add(sensorName);
		
		JLabel upperAlarmVal = new JLabel("upperLimit: " + Double.toString(sensor.getupperLimit()) + "\u00b0C");
		info.add(upperAlarmVal);
		
		JLabel lowerAlarmVal = new JLabel("lowerLimit: " + Double.toString(sensor.getlowerLimit()) + "\u00b0C");
		info.add(lowerAlarmVal);
		
		JLabel newUpperAlarmVal = new JLabel("New Maximum value: ");
		info.add(newUpperAlarmVal);
		
		SpinnerModel uppermodel = new SpinnerNumberModel(sensor.getupperLimit(), 0, 1000, 1);
		upperPicker = new JSpinner(uppermodel);
		info.add(upperPicker);
		
		JLabel newLowerAlarmVal = new JLabel("New Minimun value:");
		info.add(newLowerAlarmVal);
		
		SpinnerModel lowermodel = new SpinnerNumberModel(sensor.getlowerLimit(), 0, 1000, 1);
		lowerPicker = new JSpinner(lowermodel);
		info.add(lowerPicker);
		
		JLabel history = new JLabel("Historic: " + sensor.getLast10());
		info.add(history);
		
		JLabel max = new JLabel("Max: " + sensor.getMaximum());
		info.add(max);
		JLabel min = new JLabel("Min: " + sensor.getMinimum());
		info.add(min);
		JLabel avr = new JLabel("Avr: " + sensor.getAverage());
		info.add(avr);
		
		JButton submit = new JButton("OK");
		submit.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				Double resultDouble = (Double) upperPicker.getValue();
				int newUp = resultDouble.intValue();
				resultDouble = (Double) lowerPicker.getValue();
				int newLow = resultDouble.intValue();
				if(newLow>newUp){
					new ErrorBox("Minimun value can't be higher than maximum value!");
				}
				else {
					sensor.setupperLimit(newUp);
					sensor.setlowerLimit(newLow);
					popup.dispose();
				}
				
			}
		});
		info.add(submit);
		
		JPanel graph = new graphLabel(sensor);
		
		popup.add(graph);
		popup.add(info);
		
		popup.setVisible(true);		
	}
}
